/*
 * @Author: Badcandy 568197314@qq.com
 * @Date: 2022-12-18 15:05:08
 * @LastEditors: badcandy 568197314@qq.com
 * @LastEditTime: 2023-02-18 20:30:36
 * @FilePath: /dcollege/src/utils/axios.ts
 * @Description: axios封装,如有不懂请联系管理员
 * 
 * Copyright (c) 2022 by Badcandy 568197314@qq.com, All Rights Reserved. 
 */
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse,AxiosError } from 'axios'
import { Snackbar } from '@varlet/ui'
import router from '../router/index';

type Result<T> = {
  code: number;
  message: string;
  result: T;
};

export class Request {
  // axios实例
  instance: AxiosInstance
  // 基础配置
  baseConfig: AxiosRequestConfig = {baseURL:'http://8.142.107.97:8909/digital/college',timeout:5000}

  constructor(config:AxiosRequestConfig) {
    this.instance = axios.create(Object.assign(this.baseConfig,config))
    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        // 为请求头添加token
        if(localStorage.getItem('token')) {
          const token = localStorage.getItem('token') as string;
          config.headers!.token = token;
        }

        return config
      },(err: AxiosError) => {
        Snackbar.error("请求失败！"+err.message)
        return Promise.reject(err)
      }
    )
      // 响应拦截器
    this.instance.interceptors.response.use(
      (res:AxiosResponse) =>{
        return res;
      },(err: AxiosError) => {
        let message = '';
        switch (err.response!.status){
          case 50000:
            message = '业务异常(50000)';
            break;
          case 40010:
            message = '认证异常(40010)，请重新登陆';
            router.push('/login')
            break;
          default:
            message = `连接出错(${err.response!.status})!`
        }
        Snackbar.error(message)
        return Promise.reject(err.response)
      }
      // function (response) {
      //   return response
      // }, function(error) {
      //   return Promise.reject(error)
      // }
    )
  }

  public request(config: AxiosRequestConfig):Promise<AxiosResponse> {
    return this.instance.request(config)
  }

  public get<T = any>(
    url: string,
    params?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    return this.instance.get(url, params);
  }

  public post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    return this.instance.post(url, data, config);
  }

  public put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    return this.instance.put(url, data, config);
  }

  public delete<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    return this.instance.delete(url, config);
  }
}

export default new Request({})